package com.bizmerce.ebms.util;

public class Base64Util {

	public static byte[] decode(String base64Src) {
		int pad = 0;
		String base64 = base64Src;
		if (base64.length() % 4 != 0)
			System.out
					.println("Data is not Base64 encoding type.(Data length error)");

		if (!(isBase64(base64.getBytes())))
			System.out
					.println("Data is not Base64 encoding type.(String set error)");

		for (int i = base64.length() - 1; base64.charAt(--i) == '=';)
			++pad;

		int base64Length = base64.length() * 6 / 8 - pad;

		byte[] raw = new byte[base64Length];

		int rawIndex = 0;
		for (int i = 0; i < base64.length(); i += 4) {
			int block = (getValue(base64.charAt(i)) << 18)
					+ (getValue(base64.charAt(i + 1)) << 12)
					+ (getValue(base64.charAt(i + 2)) << 6)
					+ getValue(base64.charAt(i + 3));

			for (int j = 0; (j < 3) && (rawIndex + j < raw.length); ++j)
				raw[(rawIndex + j)] = (byte) (block >> 8 * (2 - j) & 0xFF);
			rawIndex += 3;
		}

		return raw;
	}

	protected static int getValue(char c) {
		if ((c >= 'A') && (c <= 'Z'))
			return (c - 'A');
		if ((c >= 'a') && (c <= 'z'))
			return (c - 'a' + 26);
		if ((c >= '0') && (c <= '9'))
			return (c - '0' + 52);
		if (c == '+')
			return 62;
		if (c == '/')
			return 63;
		if (c == '=')
			return 0;

		return -1;
	}

	public static boolean isBase64(byte[] data) {
		for (int i = 0; i < data.length; ++i) {
			char c = (char) data[i];

			if ((((c < 'A') || (c > 'Z'))) && (((c < 'a') || (c > 'z')))
					&& (((c < '0') || (c > '9'))) && (c != '+') && (c != '/')) {
				if (c == '=')
					continue;

				return false;
			}
		}
		return true;
	}
}
